package com.ytkj.ygAssist.main;

import com.ytkj.ygAssist.server.GetDataBy66w;
import com.ytkj.ygAssist.server.GetGoodsInfo;
import com.ytkj.ygAssist.server.GetUserBuyMonitorServer;
import com.ytkj.ygAssist.server.GetUserBuyServer;
import com.ytkj.ygAssist.server.SelectAssistPublishs;
import com.ytkj.ygAssist.server.util.HttpGetUtil;
import com.ytkj.ygAssist.tools.CacheData;
import com.ytkj.ygAssist.tools.JFrameListeningInterface;
import com.ytkj.ygAssist.tools.MyLog;
import com.ytkj.ygAssist.view.MainJFrame;
import com.ytkj.ygAssist.viewControl.IntelligentMonitoringControl;

import org.apache.http.impl.client.CloseableHttpClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/*
 * 云购监控服务
 */
public class IntelligentMonitoringServer {
	private static IntelligentMonitoringServer yunGouRemindServer = null;
	private String goodsID = null;// 商品ID
	private String newestPeriod = null;// 最新期数
	private String EIdx = null;// 查询多少期
	private Timer timer = null;// 监听进度条事件
	private Timer timerZeroize = null;// 监听走势是否遗漏事件
	private JFrameListeningInterface foreknowInterface;
	private String codeID = null;
	private String newestCodeID = null;// 最新期数网址id
	private boolean isNews = true;// 是否开了新一期
	private CloseableHttpClient HttpClient = null;// 查询使用HTTPClient
	private ArrayList<Thread> threadList = new ArrayList<Thread>();// 线程

	private int selectMonitorNum = 0;// 记录监听进度条查询次数
	private String[] shopCartNewString = null;// 记录商品剩余情况
	private Timer timer1 = null;// 监听进度条事件
	public static IntelligentMonitoringServer getIntelligentMonitoringServer() {
		if (yunGouRemindServer == null) {
			yunGouRemindServer = new IntelligentMonitoringServer();
		}
		return yunGouRemindServer;
	}

	public void setRemindServer(String goodsID, String EIdx, JFrameListeningInterface foreknowInterface) {
		if (CacheData.getGoodsNameCacheDate(goodsID) == null) {
			if (!GetGoodsInfo.getGoodsInfoByGoodsID(goodsID)) {
				foreknowInterface.setFrameText("setGoodsNameError", null);
				return;
			}
		}
		CacheData.setGoodsTreeListCacheDate(goodsID);
		foreknowInterface.setFrameText("setGoodsName", CacheData.getGoodsNameCacheDate(goodsID));

		this.EIdx = EIdx;
		this.foreknowInterface = foreknowInterface;
		this.goodsID = goodsID;
		this.HttpClient = HttpGetUtil.createHttpClient();
		codeID = CacheData.getGoodsInfoCacheDate(goodsID)[2];
		//String text[] = GetGoodsInfo.shopCartNew(codeID, HttpClient);
//		String text[] = GetGoodsInfo.shopCartNewByHtml(goodsID, HttpClient);
		String text[] = GetGoodsInfo.getGoodsSalingByGoodsID(goodsID, HttpClient);
		newestPeriod = text[1];
		newestCodeID = text[0];
		shopCartNewString = text;
		foreknowInterface.setFrameListeningText("1", text);
		try {
			CacheData.setGoodsPriceCacheDate(goodsID, Integer.parseInt(text[3]));
		} catch (Exception e) {
		}
		setChart();
		runRemindServer();
		runZeroizeServer();
	}

	/*
	 * 设置曲线图
	 */
	private void setChart() {
		boolean isHavaData = true;
		final ConcurrentHashMap<String, String[]> selectCacheDateMap = CacheData.getSelectCacheDate(goodsID);
		try {
			int newPeriod = Integer.parseInt(newestPeriod);
			for (int i = 1; i < Integer.parseInt(EIdx) && i < newPeriod; i++) {
				String[] cacheDateStr = selectCacheDateMap.get(Integer.toString(newPeriod - i));
				if (cacheDateStr == null) {
					isHavaData = false;
				} else {
					foreknowInterface.setFrameListeningText("3", cacheDateStr);
				}
			}
		} catch (Exception e) {
		}
		final boolean isSelect = !isHavaData;
		new Thread(new Runnable() {
			public void run() {
				if (isSelect) {
					SelectAssistPublishs.getYungouPublishs(goodsID, "0", EIdx);
				}
				List<Map<String, String>> contentList = GetGoodsInfo.getBarcodeRaffListByGoodsID(goodsID, EIdx);
				for (final Map<String, String> map : contentList) {
					final String codePeriod = map.get("codePeriod");
					String[] SelectText = selectCacheDateMap.get(codePeriod);
					final String codeRNO = map.get("codeRNO");
					if (SelectText != null) {
						if (!codeRNO.equals("") && !SelectText[2].equals(codeRNO)) {
							MyLog.outLog("计算结果错误了", goodsID, codePeriod, "原", SelectText[2], "正确", codeRNO);
							SelectAssistPublishs.deleteYungouPublish(goodsID, codePeriod);
							CacheData.removeSelectCacheDate(goodsID, codePeriod);
							SelectText = null;
						}
					}
					if (SelectText == null) {
						Thread thread = new Thread(new Runnable() {
							public void run() {
								if (map.get("codeState").equals("1")) {
								} else {
									String codeID = map.get("codeID");
									if (codeRNO.equals("")) {
										GetUserBuyServer.getUserBuyServer(codeID).GetGoodsPeriodInfo(goodsID,
												codePeriod, codeID, false);
									} else {
										GetUserBuyServer getUserBuyServer = GetUserBuyServer.getUserBuyServer(codeID);
										getUserBuyServer.setBarcodernoInfo(codeRNO, map.get("userName"),
												map.get("userWeb"));
										getUserBuyServer.GetGoodsPeriodInfo(goodsID, codePeriod, codeID, false);
									}
								}
							}
						});
						thread.start();
						threadList.add(thread);
					} else {
						foreknowInterface.setFrameListeningText("3", SelectText);
					}
				}
			}
		}).start();
	}
//	private void testServer(){
//		if (isNews) {
//			
//		
//		
//		}
//	}

	/*
	 * 监控商品
	 */
	private void runRemindServer() {
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				String text[];
				if (selectMonitorNum++ >= 3) {
					selectMonitorNum = 0;
//					text = GetGoodsInfo.shopCartNew(codeID, HttpClient);
//					text = GetGoodsInfo.shopCartNewByHtml(goodsID, HttpClient);
					text = GetGoodsInfo.getGoodsSalingByGoodsID(goodsID, HttpClient);
//					MyLog.outLog("电脑监听购买情况", text);
				} else {
					text = GetDataBy66w.shopCartNew(goodsID);
					text[0] = codeID;
//					MyLog.outLog("66网监听购买情况", text);
				}
				if (text != null) {
					foreknowInterface.setFrameText("refresProgressBar", null);
					try {
						if (Integer.parseInt(text[1]) == Integer.parseInt(shopCartNewString[1])) {
							if (Integer.parseInt(text[2]) <= Integer.parseInt(shopCartNewString[2])) {
								return;
							}
						} else if (Integer.parseInt(text[1]) < Integer.parseInt(shopCartNewString[1])) {
							return;
						}
						shopCartNewString = text;
						foreknowInterface.setFrameListeningText("2", text);
						if (!text[1].equals(newestPeriod)) {
							if (isNews) {
								isNews = false;
								foreknowInterface.setFrameText("newestCodeID", text[0]);
								foreknowInterface.setFrameText("newestPeriod", text[1]);
								final String periodString = newestPeriod;
								final String codeIDstring = newestCodeID;
									new Timer().schedule(new TimerTask() {
										@Override
										public void run() {
											MyLog.outLog("开始查询最新云购", periodString, codeIDstring);
											timer1 = new Timer();
											timer1.schedule(new TimerTask() {
												@Override
												public void run() {
													IntelligentMonitoringControl intelligentMonitoring = (IntelligentMonitoringControl) MainJFrame
															.getMainJFrame().getTabbedPaneSelected(1);
													ArrayList<String> values = intelligentMonitoring.getNotData();
													for (String period : values) {
													MyLog.outLog("提前查服务器", goodsID, period);
													SelectAssistPublishs.getYungouPublishs(goodsID, period, "1");
													if (CacheData.getSelectCacheDate(goodsID, period) != null){
														foreknowInterface.setFrameListeningText("3", CacheData.getSelectCacheDate(goodsID, period));
													}
													}
													
												}
											}, 0, 500);
											GetUserBuyServer.getUserBuyServer(codeIDstring).GetGoodsPeriodInfo(goodsID,
													periodString, codeIDstring, false);
										}
									}, 6000);
									newestPeriod = text[1];
									newestCodeID = text[0];
									new Timer().schedule(new TimerTask() {
										@Override
										public void run() {
											GetUserBuyMonitorServer.selectBarcodernoInfo(goodsID, newestPeriod,
													newestCodeID);
										}
									}, 4000);
									isNews = true;
							}
						}
					} catch (Exception e) {
					}
				}
			}
		}, 64, 64);

		GetUserBuyMonitorServer.selectBarcodernoInfo(goodsID, newestPeriod, newestCodeID);
	}

	private void runZeroizeServer() {
		timerZeroize = new Timer();
		timerZeroize.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					IntelligentMonitoringControl intelligentMonitoring = (IntelligentMonitoringControl) MainJFrame
							.getMainJFrame().getTabbedPaneSelected(1);
					ArrayList<String> values = intelligentMonitoring.getNotData();
					for (String period : values) {
						MyLog.outLog("检测到为零", period);
						SelectAssistPublishs.getYungouPublishs(goodsID, period, "1");
						if (CacheData.getSelectCacheDate(goodsID, period) == null) {
							String[] content = GetGoodsInfo.getGoodsPeriodInfo(goodsID, period);
							try {
								if (content[0].equals("2")) {
									// GetUserBuyServer.getUserBuyServer(content[1]).GetGoodsPeriodInfo(goodsID,
									// period,
									// content[1], false);
								} else if (content[0].equals("3")) {
									GetUserBuyServer.getUserBuyServer(content[1]).GetGoodsPeriodInfo(goodsID, period,
											content[1], true);
								}
							} catch (Exception e) {
							}
						} else {
							foreknowInterface.setFrameListeningText("3", CacheData.getSelectCacheDate(goodsID, period));
						}
					}
				} catch (Exception e) {
				}
			}
		}, 6000, 5000);
	}

	public void stopRemindServer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timer1 != null) {
			timer1.cancel();
			timer1 = null;
		}
		if (timerZeroize != null) {
			timerZeroize.cancel();
			timerZeroize = null;
		}
		for (Thread thread : threadList) {
			thread.stop();
			thread = null;
		}
		threadList.removeAll(threadList);
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				HttpGetUtil.CloseHttpClient(HttpClient);
				foreknowInterface.setFrameText("stopRemind", null);
			}
		}, 1000);
	}
}
